package com.yzdbx.task;

import cn.hutool.core.util.RandomUtil;
import com.yzdbx.utils.GenUtil;

import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import static com.yzdbx.utils.DbUtil.getMaxId;

/**
 * @BelongsProject: SERVEVICE-DATA-GEN
 * @BelongsPackage: com.yzdbx.task
 * @Author: lk
 * @CreateTime: 2025-05-14
 * @Description: TODO
 * @Version: 1.0
 */
@SuppressWarnings("all")
public class PurchaseRunnable implements Exe {

    private Connection connection;
    private static final String ALL_SUPPLIER_SQL = "select id from  supplyManagement";
    private static final String ALL_PRODUCT_SQL = "select id from gy02ProductRepository where productClassification in ('原材料')";
    private static final String ALL_USER_SQL = "select memberId as ID from corp_member";
    public static final ThreadLocal<List<Integer>> GEN_PURCHASE_IDS = new ThreadLocal<>();
    private static final int BATCH_SIZE = 3;


    public PurchaseRunnable(Connection connection) {
        this.connection = connection;
    }

    public boolean execute(int count) {
        List<Integer> genPurchaseIds = new ArrayList<>(count);
        int batchCount = 0;
        boolean originalAutoCommit = true;
        try {
            // 保存原始自动提交状态
            originalAutoCommit = connection.getAutoCommit();
            
            // 查询供应商信息
            List<Integer> supplierIds = new ArrayList<>();
            try (PreparedStatement statement = connection.prepareStatement(ALL_SUPPLIER_SQL);
                 ResultSet resultSet = statement.executeQuery()) {
                while (resultSet.next()) {
                    supplierIds.add(resultSet.getInt("ID"));
                }
            }

            // 查询产品信息
            List<Integer> productIds = new ArrayList<>();
            try (PreparedStatement statement = connection.prepareStatement(ALL_PRODUCT_SQL);
                 ResultSet resultSet = statement.executeQuery()) {
                while (resultSet.next()) {
                    productIds.add(resultSet.getInt("ID"));
                }
            }

            // 查询用户信息
            List<String> userIds = new ArrayList<>();
            try (PreparedStatement statement = connection.prepareStatement(ALL_USER_SQL);
                 ResultSet resultSet = statement.executeQuery()) {
                while (resultSet.next()) {
                    userIds.add(resultSet.getString("ID"));
                }
            }

            int maxOrderId = getMaxId(connection, "cgPurchaseOrderForms");
            int maxDetailId = getMaxId(connection, "breakdownOfPurchaseOrders");

            // 准备批量插入语句
            String detailSql = "insert into breakdownOfPurchaseOrders (id,procurementInformation,procurementVolume,unitPrice,numberOfShipmentsArrived,numberOfRefunds,associatedPurchaseOrders,f739,f12e) values (?,?,?,?,?,?,?,?,?)";
            String purchaseSql = "insert into cgPurchaseOrderForms (id,purchaseOrderNumber,chiefProcurementOfficer,dateOfProcurement,associatedSuppliers,auditStatus,procurementVolume,amountProcured,numberOfShipmentsArrived,amountOfGoodsToBeDelivered,synchronisingFolderFailedSS,created) values (?,?,?,?,?,?,?,?,?,?,?,?)";

            try (PreparedStatement detailStatement = connection.prepareStatement(detailSql);
                 PreparedStatement purchaseStatement = connection.prepareStatement(purchaseSql)) {

                // 设置手动提交
                connection.setAutoCommit(false);


                for (int i = 1; i <= count; i++) {
                    int orderCount = 0;
                    BigDecimal totalPrice = BigDecimal.ZERO;
                    int curOrderId = ++maxOrderId;
                    genPurchaseIds.add(curOrderId);

                    // 生成采购订单明细
                    int detailCount = RandomUtil.randomInt(1, 4);
                    List<Integer> proIds = new ArrayList<>();

                    for (int j = 1; j <= detailCount; j++) {
                        int curDetailId = ++maxDetailId;
                        detailStatement.setInt(1, curDetailId);
                        detailStatement.setInt(2, GenUtil.getNoRepeatId(RandomUtil.randomEle(productIds), proIds, productIds));
                        int number = RandomUtil.randomInt(2, 3000);
                        detailStatement.setInt(3, number);
                        BigDecimal unitPrice = RandomUtil.randomBigDecimal(BigDecimal.ONE, BigDecimal.valueOf(20)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        detailStatement.setBigDecimal(4, unitPrice);
                        detailStatement.setInt(5, number);
                        detailStatement.setInt(6, 0);
                        detailStatement.setInt(7, curOrderId);
                        detailStatement.setTimestamp(8, GenUtil.CUR_TIME_STAMP.get());
                        detailStatement.setString(9, RandomUtil.randomEle(userIds));
                        orderCount += number;
                        totalPrice = totalPrice.add(unitPrice.multiply(BigDecimal.valueOf(number)));
                        detailStatement.addBatch();
                    }

                    // 设置采购订单信息
                    String userId = RandomUtil.randomEle(userIds);
                    purchaseStatement.setInt(1, curOrderId);
                    purchaseStatement.setString(2, GenUtil.getNo("CGDD", i));
                    purchaseStatement.setString(3, userId);
                    purchaseStatement.setDate(4, Date.valueOf(GenUtil.CUR_DATE.get()));
                    purchaseStatement.setInt(5, RandomUtil.randomEle(supplierIds));
                    purchaseStatement.setString(6, "已通过");
                    purchaseStatement.setInt(7, orderCount);
                    purchaseStatement.setBigDecimal(8, totalPrice);
                    purchaseStatement.setInt(9, orderCount);
                    purchaseStatement.setBigDecimal(10, totalPrice);
                    purchaseStatement.setString(11, userId);
                    purchaseStatement.setTimestamp(12, GenUtil.CUR_TIME_STAMP.get());
                    purchaseStatement.addBatch();

                    batchCount++;
                    // 每BATCH_SIZE条记录执行一次批量插入
                    if (batchCount >= BATCH_SIZE) {
                        detailStatement.executeBatch();
                        purchaseStatement.executeBatch();
                        connection.commit();
                        batchCount = 0;
                    }
                }

                // 执行剩余的批量插入
                if (batchCount > 0) {
                    detailStatement.executeBatch();
                    purchaseStatement.executeBatch();
                    connection.commit();
                }

            }

        } catch (Exception e) {
            try {
                if (!connection.getAutoCommit()) {
                    connection.rollback();
                }
            } catch (SQLException ex) {
                throw new RuntimeException("回滚失败", ex);
            }
            throw new RuntimeException("数据生成失败", e);
        } finally {
            try {
                // 恢复原始自动提交状态
                connection.setAutoCommit(originalAutoCommit);
            } catch (SQLException e) {
                throw new RuntimeException("恢复自动提交状态失败", e);
            }
        }

        GEN_PURCHASE_IDS.set(genPurchaseIds);
        return Boolean.TRUE;
    }
}
